package com.kuaiditu.assistant.ui.main;


import android.Manifest;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kuaiditu.assistant.R;
import com.kuaiditu.assistant.api.assistant_api.AssistantApi;
import com.kuaiditu.assistant.api.assistant_api.base.AssistantResponse;
import com.kuaiditu.assistant.api.assistant_api.respone.TaskSquareRes;
import com.kuaiditu.assistant.base.BaseFragment;
import com.kuaiditu.assistant.entity.TaskSquareEn;
import com.kuaiditu.assistant.module.retrofit.ProgressSubscriber;
import com.kuaiditu.assistant.service.LocationService;
import com.kuaiditu.assistant.ui.dialog.TaskInfoDialog;
import com.kuaiditu.assistant.ui.message.MessageActivity;
import com.kuaiditu.assistant.ui.profile.ProfileActivity;
import com.kuaiditu.assistant.util.ToastUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.iwgang.simplifyspan.SimplifySpanBuild;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DefaultObserver;

public class TaskSquareFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    public static final String TAG = "TaskSquareFragment";


    RecyclerView mRvTask;

    List<TaskSquareEn> tasks = new ArrayList<>();
    TaskAdapter mTaskAdapter;
    @BindView(R.id.swiper)
    SwipeRefreshLayout swiper;
    Unbinder unbinder;

    AssistantApi mAssistantApi;

    private boolean isRefresh;
    private int page = 1;
    private int count = 0;

    @Autowired
    LocationService mLocationService;

    RxPermissions rxPermissions;


    @Override
    public void initInjector() {
        mAssistantApi = getApplicationComponent().getApiManager().getAssistantApi();

        ARouter.getInstance().inject(this);

        rxPermissions = new RxPermissions(getActivity());
    }

    @Override
    public int initContentView() {
        return R.layout.fragment_task_square;
    }

    @Override
    public void getBundle(Bundle bundle) {

    }

    @Override
    public void initUI(View view) {

        unbinder = ButterKnife.bind(this, view);

        mRvTask = (RecyclerView) view.findViewById(R.id.rv_task);
        mRvTask.setLayoutManager(new LinearLayoutManager(mContext));
        mRvTask.setAdapter(mTaskAdapter = new TaskAdapter(tasks, mLocationService));


        mTaskAdapter.setOnItemChildClickListener(this);
        mTaskAdapter.setOnLoadMoreListener(this, mRvTask);
        mTaskAdapter.setEnableLoadMore(true);


        view.findViewById(R.id.img_profile)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ARouter.getInstance().build(ProfileActivity.PATH)
                                .navigation();
                    }
                });
        view.findViewById(R.id.img_msg)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ARouter.getInstance().build(MessageActivity.PATH)
                                .navigation();
                    }
                });




        swiper.setOnRefreshListener(this);

        onRefresh();

        rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribe(new DefaultObserver<Boolean>() {
                    @Override
                    public void onNext(@NonNull Boolean aBoolean) {
                        if (aBoolean) {
                            mLocationService.start();
                        } else {
                            ToastUtil.showToast("定位权限被禁止，部分功能不能正常运行");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    @Override
    public void initData() {

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        swiper.setRefreshing(true);
        mTaskAdapter.setEnableLoadMore(true);
        page = 1;
        fetchTask();
    }


    private void fetchTask() {
        mAssistantApi.fetchTask(page)
                .subscribe(new ProgressSubscriber<TaskSquareRes>(mContext, "获取任务中...") {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(TaskSquareRes taskSquareRes) {
                        if (isRefresh) {
                            tasks.clear();
                        }

                        List<TaskSquareEn> taskSquareEns = taskSquareRes.getListOrder();
                        count = taskSquareRes.getOrderCount();

//                        if (tasks.size() >= taskSquareRes.getOrderCount()) {
//
//
//                        } else {

                        mTaskAdapter.loadMoreComplete();
                        page++;
//                        }
                        tasks.addAll(taskSquareRes.getListOrder());
                    }

                    @Override
                    public void onFinish() {
                        isRefresh = false;
                        swiper.setRefreshing(false);
                        mTaskAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void fetchTaskDes(final int id) {
        mAssistantApi.fetchTaskDes(id)
                .subscribe(new ProgressSubscriber<JSONObject>(mContext) {

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(JSONObject json) {
                        JSONArray infos = json.getJSONArray("info");
                        List<String> infoStr = new ArrayList<>();
                        for (int i = 0; i < infos.size(); i++) {
                            infoStr.add(infos.getString(i));
                        }

                        SimplifySpanBuild spanBuild = new SimplifySpanBuild();
                        int size = infoStr.size();
                        for (int i = 0; i < size; i++) {
                            spanBuild.append(infoStr.get(i));
                            if (i < size - 1) {
                                spanBuild.append("\n");
                            }
                        }


                        TaskInfoDialog taskInfoDialog = (TaskInfoDialog) ARouter.getInstance().build(TaskInfoDialog.PATH).navigation();
                        taskInfoDialog.setMessage(spanBuild.build());
                        taskInfoDialog.setOnTakeTaskClickListener("确定接单", new TaskInfoDialog.onTakeTaskClickListener() {
                            @Override
                            public void onClick() {
                                takeTask(String.valueOf(id));
                            }
                        });
                        taskInfoDialog.show(getChildFragmentManager(), TaskInfoDialog.PATH);


                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        TaskAdapter taskAdapter = (TaskAdapter) adapter;
        TaskSquareEn taskSquareEn = taskAdapter.getData().get(position);

        switch (view.getId()) {
            case R.id.btn_take_task:
                fetchTaskDes(taskSquareEn.getOrder_id());
                break;
        }
    }


    private void takeTask(String task_id) {
        mAssistantApi.takeTask(task_id)
                .subscribe(new ProgressSubscriber<AssistantResponse>(mContext) {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(AssistantResponse responseBody) {
                        onRefresh();
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    @Override
    public void onLoadMoreRequested() {
        if (tasks.size() < count) {
            fetchTask();
        } else {
            mTaskAdapter.loadMoreEnd(false);
            mTaskAdapter.setEnableLoadMore(false);
        }
    }



    public void noticeChange() {
        mTaskAdapter.notifyDataSetChanged();
    }
}
